import { setData, saveOtherProduct, getProductChecked, formatDate, deleteRightTodo, deleteRightItem, getSaleNum, getValueArray, setEmptyArray, setArrayValue } from '@/views/sales/common/TableSaleMethods'
import { ajaxGet, jsonPost } from '@/util'
import { Notice } from 'view-design'
export default ({
  state: {
    saleData: '',
    saleDarkData: '',
    GetsaleData: '',
    FullreturnForm: {
      name: '',
      date: '',
      remarks: '',
      gender: '2',
      returnType: '1',
      endTime: '',
      time: '',
      type: '',
      joinType: '2',
      grade: [],
      selectProductNum: '',
      activityGiftCouponList: [{
        'value': '',
        'denomination': '',
        'useCondition': '',
        'validityDays': '',
        'custom': '',
        isParcel: false
      }],
      giftCoupon: [],
      returnTypeList: [{
        value: '',
        couponId: '',
        isParcel: false
      }]
    },
    searchForm: {
      brandId: null,
      ownerCategoryId: null,
      keyword: '',
      code: '',
      skuCode: '',
      tireFigure: '',
      tireRim: '',
      specs: ''
    }
  },
  mutations: {
    onSetOtherSearch (state, param) {
      state.searchForm.brandId = param.brandId
      state.searchForm.ownerCategoryId = param.ownerCategoryId
      state.searchForm.keyword = param.keyword
      state.searchForm.code = param.code
      state.searchForm.skuCode = param.skuCode
      state.searchForm.tireFigure = param.tireFigure
      state.searchForm.tireRim = param.tireRim
      state.searchForm.specs = param.specs
    },
    setSetOtherSearchEmpty (state) {
      state.searchForm.brandId = null
      state.searchForm.ownerCategoryId = null
      state.searchForm.keyword = ''
      state.searchForm.code = ''
      state.searchForm.skuCode = ''
      state.searchForm.tireFigure = null
      state.searchForm.tireRim = null
      state.searchForm.specs = null
    },
    onAddvoucher (state) { //满额返劵增加优惠劵
      if (state.FullreturnForm.activityGiftCouponList.length < 3) {
        state.FullreturnForm.activityGiftCouponList.push({
          'value': '',
          'denomination': '',
          'useCondition': '',
          'validityDays': '',
          'custom': '',
          isParcel: false
        })
      }
    },
    onAddType (state) {
      // if (state.FullreturnForm.returnTypeList.length < 3) {
      state.FullreturnForm.returnTypeList.push({
        value: '',
        couponId: '',
        isParcel: false
      })
      // }
    },
    onReduceType (state, index) {
      state.FullreturnForm.returnTypeList.splice(index, 1)
    },
    onReducevoucher (state, index) {
      state.FullreturnForm.activityGiftCouponList.splice(index, 1)
    },
    getFullReturnSaleData (state, param) {
      let getdata = JSON.parse(JSON.stringify(state.saleData))
      getValueArray(getdata, { index: param.type, childName: 'productSkuList', status: false })
      setEmptyArray(getdata, { index: param.type, childName: 'productSkuList' })
      setArrayValue(getdata, { index: param.type, val1: false, childName: 'productSkuList' })
      // 获取选中的商品
      if (!getProductChecked(getdata).length) {
        Notice.warning({
          title: '温馨提示',
          desc: '请选择主商品'
        })
        return
      }
      // 提交选中的商品
      saveOtherProduct(state, param, getProductChecked(getdata))
      // if (!state.GetsaleData.length) { //首次为空
      //   state.GetsaleData = getdata
      // } else { // 防止每次更新的淹没其他的
      //把没有的第一层数据存在，GetsaleData里面
      //把没有的第二层的数据存在, GetsaleData里面
      //   spliceGetDataItem(getdata, state.GetsaleData)
      //   spliceGetDataTodo(getdata, state.GetsaleData)
      // }
      // if (type !== 'buttonChecked') {
      //   setExchangeValue(state.saleData, { index1: 'checked', index: 'buttonChecked',  childName: 'productSkuList'})
      // }
    },
    deleteFullReturn (state, object) {
      if (object.todo && !object.todo.buttonChecked || object.item && !object.item.buttonChecked) {
        if (object.todo) { //没子集
          deleteRightTodo(object.item, object.todo, state.GetsaleData)
        } else { //有子集
          deleteRightItem(object.item, state.GetsaleData)
        }
      }
    },
    onFullReturnSelectAll (state, param) {
      param ? setArrayValue(state.saleData, {
        index: 'checked',
        val1: true,
        childName: 'productSkuList'
      }) : setArrayValue(state.saleData, {
        index: 'checked',
        val1: false,
        childName: 'productSkuList'
      })
    },
    setFullreturnSaleEmpty (state) {
      state.GetsaleData = ''
      state.saleData = ''
      state.FullreturnForm = {
        name: '',
        date: '',
        remarks: '',
        gender: '2',
        returnType: '1',
        endTime: '',
        time: '',
        type: '',
        joinType: '2',
        grade: [],
        selectProductNum: '',
        activityGiftCouponList: [{
          'value': '',
          'denomination': '',
          'useCondition': '',
          'validityDays': '',
          'custom': '',
          isParcel: false
        }],
        giftCoupon: [],
        returnTypeList: [{
          value: '',
          couponId: '',
          isParcel: false
        }]
      }
      state.searchForm = {
        brandId: null,
        ownerCategoryId: null,
        keyword: '',
        code: '',
        skuCode: '',
        tireFigure: '',
        tireRim: '',
        specs: ''
      }
    },
    setOtherSkuPage (state, data) {
      state.GetsaleData = setData(data)
    }
  },
  actions: {
    getOtherSkuPage ({ state, commit }, param) {
      let params = {
        activityId: param.activityId,
        current: param.current, size: param.size,
        storeCategoryId: state.searchForm.ownerCategoryId,
        productName: state.searchForm.keyword,
        productBrandId: state.searchForm.brandId,
        tireFigure: state.searchForm.tireFigure,
        tireRim: state.searchForm.tireRim,
        specs: state.searchForm.specs
      }
      return new Promise((resolve, reject) => {
        ajaxGet(`/activity/sku/page`, params).then(data => {
          commit('setOtherSkuPage', data)
          let self = param.self
          self.status = 'pass'
          self.currentPage = Number(data.current)
          self.totalItem = Number(data.total)
          resolve(data)
        })
      })
    },
    getOtherSkuCount ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        ajaxGet(`/activity/sku/count/${param.id}`).then(data => {
          state.FullreturnForm.selectProductNum = data
          resolve(data)
        })
      })
    },
    getGiftCouponList () {
      return new Promise((resolve, reject) => {
        ajaxGet('/coupon/coupon_info/factory_coupon').then(data => {
          resolve(data)
        })
      })
    },
    getGiftDetailData ({ state, commit }, id) {
      return new Promise((resolve, reject) => {
        ajaxGet(`/activity/full_gift_coupon/detail/${id}`).then(data => {
          resolve(data)
          state.FullreturnForm.remarks = data.activityInfoDTO.activityDescription //活动备注
          state.FullreturnForm.name = data.activityInfoDTO.activityName //促销名称
          state.FullreturnForm.gender = data.activityFullGiftCouponDTO.isFirstOrderGift ? '1' : '2' // 是否首单返券
          state.FullreturnForm.date = [new Date(data.activityInfoDTO.startDate), new Date(data.activityInfoDTO.endDate)] //用户下单时间
          state.FullreturnForm.grade = data.activityInfoDTO.storeTypeEnumList
          state.FullreturnForm.returnType = data.activityFullGiftCouponDTO.fullGiftCouponTypeEnum == 'PRODUCT' ? '1' : '2'
          let word = ''
          if (data.activityInfoDTO.joinTypeEnum == 'WHOLE') {
            word = '1'
          } else if (data.activityInfoDTO.joinTypeEnum == 'PART') {
            word = '2'
          } else {
            word = '3'
          }
          state.FullreturnForm.joinType = word
          state.FullreturnForm.endTime = new Date(data.activityFullGiftCouponDTO.limitCompleteDatetime)
          state.FullreturnForm.time = JSON.stringify(data.activityFullGiftCouponDTO.limitReturnDate)
          state.FullreturnForm.activityGiftCouponList = data.activityFullGiftCouponDTO.giftCouponRuleList.map(item => {
            return {
              value: item.m,
              denomination: 'custom',
              useCondition: '',
              validityDays: '',
              custom: ''
            }
          })
          state.FullreturnForm.returnTypeList = data.activityFullGiftCouponDTO.giftCouponRuleList.map(item => {
            return {
              value: item.m,
              couponId: item.n
            }
          })
          if (data.activityFullGiftCouponDTO.fullGiftCouponTypeEnum !== 'PRODUCT') {
            jsonPost(`/coupon/coupon_info/ids`, data.activityFullGiftCouponDTO.giftCouponIdList).then(res => {
              state.FullreturnForm.activityGiftCouponList.forEach((item, index) => {
                res.forEach((todo, index1) => {
                  if (index == index1) {
                    item.denomination = 'custom'
                    item.useCondition = todo.useCondition
                    item.validityDays = todo.validityDays
                    item.custom = todo.denomination
                  }
                })
              })
            })
          }
        })
      })
    }
  },
  getters: {
    selectProductNum (state) {
      return state.FullreturnForm.selectProductNum
    },
    getGiftParamGrade (state, getters) {
      return state.FullreturnForm.grade
    },
    getGiftGrade (state, getters) {
      let newarray = []
      for (let item of state.FullreturnForm.grade) {
        for (let todo of getters.storeTypeData) {
          if (item == todo.value) {
            newarray.push(todo.text)
          }
        }
      }
      return newarray.join(',')
    },
    getOrderCoupon (state, getters) {
      let word = ''
      state.FullreturnForm.returnTypeList.forEach(item => {
        word = word + `单个订单满${item.value}个商品返${state.FullreturnForm.giftCoupon[item.couponId]}`
      })
      return word
    },
    getGiftGender (state) {
      let word
      switch (state.FullreturnForm.joinType) {
        case '1' :
          word = '全场商品参加'
          break
        case '2' :
          word = '部分商品参加'
          break
        case '3' :
          word = '部分商品不参加'
          break
      }
      return word
    },
    getGiftFirstType (state) {
      let word
      if (state.FullreturnForm.gender == '1') {
        word = '是'
      } else {
        word = '否'
      }
      return word
    },
    getGiftJoinType (state) {
      let word = ''
      if (state.FullreturnForm.joinType == '1') {
        word = 'WHOLE'
      } else if (state.FullreturnForm.joinType == '2') {
        word = 'PART'
      } else {
        word = 'PART_NOT'
      }
      return word
    },
    getfullReturnSaleNum (state) {
      return getSaleNum(state.GetsaleData, {
        childName: 'productSkuList'
      })
    },
    getReturnType (state) {
      if (state.FullreturnForm.returnType == '2') {
        return 'MONEY'
      } else {
        return 'PRODUCT'
      }
    },
    getGiftCouponRuleList (state) {
      return state.FullreturnForm.returnTypeList.map(item => {
        return {
          m: item.value,
          n: item.couponId,
          isParcel: item.isParcel
        }
      })
    },
    getReturnGender (state) {
      if (state.FullreturnForm.gender == 1) {
        return true
      } else {
        return false
      }
    },
    getReturnTimeList (state) {
      return [{
        startDatetime: formatDate(state.FullreturnForm.date[0], true),
        endDatetime: formatDate(state.FullreturnForm.date[1], true)
      }
      ]
    },
    limitReturnCompleteDate (state) {
      return formatDate(state.FullreturnForm.endTime, true)
    }
  }
})
